package cn.jh.common.utils;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class PayUtil {
	
	/**
	 * 生成20位的数字订单号
	 * @return
	 */
	public static String getOrderIdNumber(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String str1 = sdf.format(date);
		int number = (int)((Math.random()*9+1)*100000);
		return str1 + number;
	}
	
	/**
	 * sign生成
	 * @param map
	 * @param key
	 * @return 
	 */
	public static String parseSign(Map<String,String> map,String key){
		Collection<String> keyset= map.keySet();
		List<String> list = new ArrayList<String>(keyset);
		Collections.sort(list);
		String signStr = "";
		for(int i=0;i<list.size();i++){
			signStr += list.get(i)+"="+map.get(list.get(i));
			if(i<list.size()-1){
				signStr += "&";
			}
		}
		signStr += "&key="+key;
		System.out.println("signStr == >>"+signStr);
		String sign = DigestUtils.md5Hex(signStr).toUpperCase();
		return sign;
	}
	/**
	 * mapתjson
	 * @param map
	 * @return
	 */
	public static JSONObject mapToJson(Map<String, String> map) {
		JSONObject json = new JSONObject();
		try {
			Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> entry = it.next();
				json.put(entry.getKey(), entry.getValue());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json;
	}
	
	/**
	 * 获取地址的is
	 * @return
	 */
	public static InputStream getLinkInputStream(String link) {
		URL url = null;  
        InputStream is =null;  
        try {  
            url = new URL(link);  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        }  
        try {  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.  
            conn.setDoInput(true);  
            conn.connect();
            int code = conn.getResponseCode();
            
            if(code == 200){
            	is = conn.getInputStream(); //得到网络返回的输入流  
            }else{
            	System.out.println("signin not img link===>" + link);
            }
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return is;
	}

}
